package com.example.pingapplication2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

import com.example.pingapplication2.config.Config;
import com.example.pingapplication2.databinding.ActivityMainBinding;
import com.example.pingapplication2.net.INetListener;
import com.example.pingapplication2.net.RetrieveFeedTask;
import com.example.pingapplication2.viewModel.CountDownViewModel;
import com.example.pingapplication2.viewModel.MaxFailViewModel;
import com.example.pingapplication2.viewModel.StateViewModel;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements INetListener {
    ActivityMainBinding activityMainBinding;
    StateViewModel mStateViewModel;
    CountDownViewModel mCountDownViewModel;
    MaxFailViewModel mMaxFailViewModel;

    RetrieveFeedTask retrieveFeedTask ;

    AlertDialog.Builder builder;

    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        context = this;

        //导航栏的设置
        NavController controller = Navigation.findNavController(this, R.id.navfragment);
        NavigationUI.setupActionBarWithNavController(this, controller);

        //viewModel的初始化
        mStateViewModel = new ViewModelProvider(this).get(StateViewModel.class);
        mCountDownViewModel = new ViewModelProvider(this).get(CountDownViewModel.class);
        mMaxFailViewModel = new ViewModelProvider(this).get(MaxFailViewModel.class);

        mCountDownViewModel.start.postValue(false);
        mMaxFailViewModel.start.postValue(false);

        retrieveFeedTask = RetrieveFeedTask.getInstance(this);
        retrieveFeedTask.registerListener((INetListener) this);

        mCountDownViewModel.start.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mCountDownViewModel.set.postValue(false);
                    mCountDownViewModel.countDownPingTimer = new Timer();
                    mCountDownViewModel.countDownPingTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            retrieveFeedTask.pingThread(Config.urls, mStateViewModel.packetNum.getValue());
                        }
                    };
                    mCountDownViewModel.countDownPingTimer.scheduleAtFixedRate(mCountDownViewModel.countDownPingTimerTask, 0, 250);

                    mCountDownViewModel.countDownRunTimer = new Timer();
                    mCountDownViewModel.countDownRunTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            mCountDownViewModel.calCurTime();
                        }
                    };
                    mCountDownViewModel.countDownRunTimer.scheduleAtFixedRate(mCountDownViewModel.countDownRunTimerTask,1000,1000);
                }
            }
        });

        mMaxFailViewModel.start.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    mMaxFailViewModel.set.postValue(false);
                    mMaxFailViewModel.maxFailPingTimer = new Timer();
                    mMaxFailViewModel.maxFailPingTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            retrieveFeedTask.pingThread(Config.urls, mStateViewModel.packetNum.getValue());
                        }
                    };
                    mMaxFailViewModel.maxFailPingTimer.scheduleAtFixedRate(mMaxFailViewModel.maxFailPingTimerTask, 0, 250);


                    mMaxFailViewModel.maxFailRunTimer = new Timer();
                    mMaxFailViewModel.maxFailRunTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            mMaxFailViewModel.calCurTime();
                        }
                    };
                    mMaxFailViewModel.maxFailRunTimer.scheduleAtFixedRate(mMaxFailViewModel.maxFailRunTimerTask, 1000, 1000);
                }
            }
        });

        mMaxFailViewModel.curFailure.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if(integer >= mMaxFailViewModel.totalFailure.getValue()){
                    if(mMaxFailViewModel.maxFailRunTimer != null){
                        mMaxFailViewModel.maxFailRunTimer.cancel();
                        mMaxFailViewModel.maxFailPingTimer.cancel();
                        int time = mStateViewModel.packetNum.getValue() * 250;
                        Toast.makeText(getApplicationContext(), "测试结束，用时："+time+"ms!", Toast.LENGTH_LONG).show();
                        mStateViewModel.flag.postValue(0);
                        mMaxFailViewModel.start.postValue(false);
                        mMaxFailViewModel.curTime.postValue(0);
                        builder = new AlertDialog.Builder(context)
                                .setIcon(R.drawable.setup)
                                .setTitle("测试结束")
                                .setMessage("测试结束，用时："+time+"ms!")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {

                                    }
                                });
                        builder.create().show();
                    }
                }
            }
        });
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController controller = Navigation.findNavController(this, R.id.navfragment);
        return controller.navigateUp();

        //return super.onSupportNavigateUp();
    }

    @Override
    public void pingSuccess() {
        mStateViewModel.successNumAdd();
        mStateViewModel.packetNumAdd();
        mStateViewModel.calPacketLoss();
        if(mStateViewModel.flag.getValue() == 2){
            mMaxFailViewModel.curFailure.postValue(0);//当前连续失败次数置0
        }
    }

    @Override
    public void pingFailure() {
        mStateViewModel.packetNumAdd();
        mStateViewModel.failureNumAdd();
        mStateViewModel.calPacketLoss();
        if(mStateViewModel.flag.getValue() == 2){
            int i = mMaxFailViewModel.curFailure.getValue();
            i++;
            mMaxFailViewModel.curFailure.postValue(i);
        }
    }
}